<?php
/**
* 微信公众号
*/
class mc_weixin_ticket extends ms_base
{
	private $role_obj = null;
	private $create_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={ACCESS_TOKEN}';
	private $ticket_url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={TICKET}';

	function __construct($role)
	{
		parent::__construct();
		$this->role_obj = $role;
		//$this->role_obj->getAccessToken(); //获取权限令牌
	}

	//获取二维码图片
	function create($scene_id = '',$expire = 60)
	{
		$access_token = $this->role_obj->getAccessToken();
		if(!$access_token) {
			return $this->add_error('未获取微信授权令牌（Access_Token）');
		}
		$url = str_replace('{ACCESS_TOKEN}', $access_token, $this->create_url);

		$post = array(
			'expire_seconds' => $expire, //二维码有效期
			'action_name' => 'QR_SCENE',
			'action_info' => array (
				'scene' => array('scene_id' => $scene_id)
			),
		);
		$json_str = urldecode(json_encode($post));
		$result = $this->http_post($url, $json_str);
		if(!$result) return false;
		$json = json_decode($result);
		if($json->errcode) {
			return $this->add_error($json->errmsg.'(errcode:'.$json->errcode.')');
		}
		return $json;
	}

	//通过ticket获取二维码图片
	public function qrcode($ticket)
	{
		$url = str_replace('{TICKET}', $ticket, $this->ticket_url);
		return $this->http_get($url);
	}

	private function http_post($url, $data) {
		if(!function_exists('curl_exec')) {
			return $this->add_error('服务器PHP未开启 curl 扩展模块');
		}
        $ch = curl_init ($url);
        curl_setopt ($ch, CURLOPT_POST, 1);
        curl_setopt ($ch, CURLOPT_HEADER, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST,  false);
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        //错误记录
        $error = curl_error($ch);
        if($error) {
            $message = "微信自定义菜单提交失败\t$error\n$url";
            log_write('weixin', $message);
            return $this->add_error('提交失败。');
        }
        if(DEBUG) log_write('weixin_debug', $url."\n".$result);
        curl_close($ch);
        return $result;
	}

	private function http_get($url) {
		if(!function_exists('curl_exec')) {
			return $this->add_error('服务器PHP未开启 curl 扩展模块');
		}
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        $result =  curl_exec($ch);
        //错误记录
        $error = curl_error($ch);
        if($error) {
            $message = "微信自定义菜单提交失败\t$error\n$url";
            log_write('weixin', $message);
            return $this->add_error('提交失败。');
        }
        if(DEBUG) log_write('weixin_debug', $url."\n".$result);
        curl_close($ch);
        return $result;
	}
}
/** end **/